/**
 * Created by John on 2016/7/27.
 */
var microblog = require('./microblog');

module.exports.Post = Post;

function Post(user, post, time) {
    this.user = user;
    this.post = post;
    if (time) {
        this.time = time;
    } else {
        this.time = new Date();
    }
}

Post.prototype.save = function (callback) {
    var post = {
        user: this.user,
        post: this.post,
        time: this.time
    };

    microblog.connect(connect);

    function connect(db) {
        db.collection('posts', createPosts)
    }

    function createPosts(err, collection) {
        error(true, err, callback);
        collection.ensureIndex('user');
        collection.insert(post, {safe: true}, insertPost);
    }

    function insertPost(err, item) {
        error(true, err, callback);
        callback(err, item);
    }
};

Post.prototype.get = function (username, callback) {
    microblog.connect(connect);

    function connect(db) {
        db.collecion('posts', findPost);
    }

    function findPost(err, collection) {
        microblog.error(err, callback);
        var query = {};
        if (this.user) {
            qeruy.user = this.user;
        }
        var reverse = {time: -1};
        collection.find(query).sort(reverse).toArray(sendPosts);
    }

    function sendPosts(err, items) {
        microblog.error(err, callback);
        callback(err, items);
    }
};